package org.travel.app.common.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.travel.app.common.vo.ResultVO;

import java.util.HashMap;
import java.util.Map;

/**
 * @author nmm
 * @date 2024-10-2024/10/17
 * @deriction njm......
 */
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO handlerValidException(MethodArgumentNotValidException e) throws Exception{
        ResultVO resultVO=new ResultVO();
        Map<String,String> map=new HashMap<>();
        BindingResult result = e.getBindingResult();
         result.getFieldErrors().forEach(error->{
             map.put(error.getField(), error.getDefaultMessage());
         });
        String msg = new ObjectMapper().writeValueAsString(map);
        resultVO.setMap(map);
        resultVO.setCode(10002);
        return  resultVO;
    }

   @ExceptionHandler(GlobalException.class)
   public ResultVO handlerGlobalException(GlobalException e)  throws Exception{
        ResultVO resultVO=new ResultVO();
        resultVO.setCode(e.getCode());
        resultVO.setMessage(e.getMessage());
        return  resultVO;
   }


    @ExceptionHandler(Exception.class)
    public ResultVO handlerGlobalException(Exception e)  throws Exception{
        ResultVO resultVO=new ResultVO();
        e.printStackTrace();
        resultVO.setCode(500);
        resultVO.setMessage("服务器内部错误");
        return  resultVO;
    }

}